package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.AuditService;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

/**
 * ClassName : FileUploadServiceImpl
 * Package : com.atguigu.tingshu.album.service.impl
 * Description :
 * <p>
 * Author: LHZ
 * Create: 2025/7/16 20:23
 * Version: 1.0
 */
@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioClient client;

    @Autowired
    private MinioConstantProperties properties;

    @Autowired
    private AuditService auditService;

    @Override
    public String fileUpload(MultipartFile multipartFile){
        try{
            //校验验证图片内容格式是否合法
            BufferedImage bufferedImage = ImageIO.read(multipartFile.getInputStream());
            if(bufferedImage == null){
                throw new GuiguException(500, "非法图片");
            }
            //校验图片大小是否合法
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if(height > 900 || width > 900){
                throw new GuiguException(500, "图片限制900*900");
            }
            //校验图片是否合法
            String auditImageResult = auditService.auditImage(multipartFile);
            if("review".equals(auditImageResult) || "block".equals(auditImageResult)){
                throw new GuiguException(500, "图片内容不合法");
            }

            //将文件上传到MinIO
            //生成带有文件夹目录文件名称  形式：/日期/随机文件名称.后缀
            String folder = "/" + DateUtil.today();
            String fileName = IdUtil.randomUUID();
            String extName = FileNameUtil.extName(multipartFile.getOriginalFilename());
            String objName = folder + "/" + fileName + "." + extName;
            //上传文件
            String buckName = properties.getBucketName();
            client.putObject(PutObjectArgs.builder().
                    bucket(buckName).
                    object(objName).
                    stream(multipartFile.getInputStream(), multipartFile.getSize(), -1).
                    contentType(multipartFile.getContentType()).build());

            //拼接上传文件在线路径地址
            return properties.getEndpointUrl() + "/" + buckName + objName;
        }catch (Exception e){
            log.error("文件上传失败", e);
            throw new GuiguException(500, e.getMessage());
        }
    }
}